package com.leetcode;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

/**
 * 347. 前 K 个高频元素
 * 通过堆排序 时间复杂度O(nlogk)
 */
public class Solution347 {

    public int[] topKFrequent(int[] nums, int k) {
        final Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
        // java默认的堆是最小堆，这里通过外部的map.get来排序
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(Comparator.comparingInt(map::get));
        for (Integer num : map.keySet()) {
            if (priorityQueue.size() >= k) {
                if (map.get(num) > map.get(priorityQueue.peek())) {
                    priorityQueue.poll();
                    priorityQueue.offer(num);
                }
            } else {
                priorityQueue.offer(num);
            }
        }
        int[] res = new int[k];
        int index = 0;
        while (!priorityQueue.isEmpty()) {
            res[index] = priorityQueue.poll();
            index++;
        }
        return res;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{1, 3, 1, 2, 1, 2, 2, 3, 3, 3, 1};
        int k = 2;
        int[] res = new Solution347_1().topKFrequent(nums, k);
        for (int num : res) {
            System.out.println(num + " ");
        }
        System.out.println();
    }

}
